/* eslint-disable */
const role = require('../model/user/role');
const User = require('../model/user/user');
const Rule = require('../model/user/rule');

const find = async (username) => {
    let isFind = await User.findOne({
        where: { username },
        attributes: ['username', 'role_id', 'status'],
        include: [{
            association: User.belongsTo(role, { foreignKey: 'role_id', target: 'id' }),
            attributes: ['rolename', 'rolekey', 'creator', 'id'],
            include: [{
                model: Rule,
                attributes: ['rulename', 'id', 'summary']
            }]
        }]
    });
    console.log(isFind.rule);
    return isFind;
};

const checkAll = async (rule, name) => {
    try {
        let event = await find(name);
        // console.log();
        if (event.status) {
            return { status: false, msg: '该用户已禁用', code: '400' };
        } else {
            if (event) {
                if(!event.role) return { status: false, msg: '权限验证未通过33', code: '400' };
                // 遍历用户权限
                let value = event.role.rules.find(item => {
                    return item.rulename === rule;
                });
                if (value) return { status: true, msg: '权限验证通过', code: '200' };
                else {
                    return { status: false, msg: '权限验证未通过11', code: '400' };
                }
            } else {
                return { status: false, msg: '权限验证未通过22', code: '400' };
            }
        }
    } catch (err) { return { msg: '操作失败', code: '400', err }; }
};

module.exports = {
    checkAll
};